<?php
require_once('simple_html_dom.php');

class ifanboy {
	
	const APP_NAME = 'ifanboy facebook app 0.01 (testing - balaclark@ymail.com)';
	
	const IFANBOY_URL = 'http://ifanboy.com';
	const IFANBOY_PULLIST_URL = 'http://ifanboy.com/users/{USER}/comics';
	const IFANBOY_PULLIST_PRINT_URL = 'http://ifanboy.com/users/{USER}/pulllist';	
	
	/**
	 * TODO: validate user details, return error if invalid.
	 * 
	 * @param $str_user
	 * @param $str_password
	 * @return unknown_type
	 */
	function ifanboy() {
		ini_set('user_agent', self::APP_NAME);
	}
	
	function pull_list($str_user) {
		
		$arr_comics = array();
		
		// format ifanboy url with username
		$str_pulllist_url = str_replace('{USER}', $str_user, self::IFANBOY_PULLIST_URL);
		
		// get html from pulllist page
		$str_html = $this->get_url_html($str_pulllist_url);
	    $obj_html = str_get_html($str_html);

	    // format comics array
	    foreach($obj_html->find('div.comics-issue') as $i => $obj_comic) {
	    	
	    	$str = trim($obj_comic->find('p', 0)->plaintext);
	    	$arr = explode(' - ', $str);
	    	
	    	$str_publisher = $arr[0];
	    	$str_price = $arr[1];
	    	
	    	$str_summary = str_replace(
	    					'href="/',
	    					'href="' . self::IFANBOY_URL . '/',
	    					trim($obj_comic->find('h3', 0)->innertext)
	    				   );
	    	
	        $arr_comics[$i] = array(
	        	'title' => trim($obj_comic->find('h2', 0)->plaintext),
	        	'summary' => $str_summary,
	        	'publisher' => $str_publisher,
	        	'price' => $str_price,
	        	'url' => self::IFANBOY_URL . trim($obj_comic->find('h2 a', 0)->href),
	        	'img' => self::IFANBOY_URL . trim($obj_comic->find('img', 0)->src),
	        );
	    }
	    
	    // clean up memory
	    $obj_html->clear();
	    unset($obj_html);
		
		return $arr_comics;
	}
	
	/**
	 * Uses curl to get the html contents of any webpage
	 * 
	 * @param string Complete url of a webpage
	 * @return string HTML string
	 */
	private function get_url_html($str_url) {
		
		$obj_curl = curl_init();

		$arr_options = array(
			CURLOPT_URL => $str_url,
			CURLOPT_RETURNTRANSFER => 1,
        	CURLOPT_HEADER => false
        );

		curl_setopt_array($obj_curl, $arr_options);
		
		$str_html = curl_exec($obj_curl);
		
		curl_close ($obj_curl);
		
		return $str_html; 
	}
}